const express = require('express');
const http = require('http');
const path = require('path');
const { readdirSync, existsSync } = require('fs');

// 动态加载所有流程文件
function getFlowFiles() {
    const flowsDir = path.join(__dirname, '.node-red', 'lib', 'flows');
    const flowFiles = [];
    
    // 检查flows目录是否存在
    if (existsSync(flowsDir)) {
        // 读取所有.json文件
        const files = readdirSync(flowsDir);
        files.forEach(file => {
            if (file.endsWith('.json')) {
                flowFiles.push(path.join(flowsDir, file));
            }
        });
    }
    
    return flowFiles;
}

// 启动Node-RED
async function startNodeRed() {
    // 动态获取所有流程文件
    const flowFiles = getFlowFiles();
    console.log('🔍 发现的流程文件:', flowFiles);
    
    // Node-RED设置
    const settings = {
        uiPort: 1880,
        mqttReconnectTime: 15000,
        serialReconnectTime: 15000,
        debugMaxLength: 1000,
        httpAdminRoot: '/red',
        httpNodeRoot: '/api',
        userDir: path.join(__dirname, '.node-red'),
        credentialSecret: "warehouse-system-secret-key",
        flowFile: path.join(__dirname, '.node-red', 'flows.json'),
        flowFilePretty: true,
        adminAuth: {
            type: "credentials",
            users: [{
                username: "admin",
                password: "$2b$08$Tf0wwbgCGbhheDqi9t7cueDSc/49jz3fAcLv.k8dm.Yemg7Z3cec.", // admin123
                permissions: "*"
            }]
        },
        editorTheme: {
            projects: {
                enabled: false
            }
        },
        functionGlobalContext: {
            // 在这里添加全局上下文
        },
        logging: {
            console: {
                level: "info",
                metrics: false,
                audit: false
            }
        }
    };
    
    // 动态导入Node-RED
    try {
        const RED = await import('node-red');
        
        // 创建Express应用
        const app = express();
        const server = http.createServer(app);
        
        // 初始化Node-RED
        RED.default.init(server, settings);
        
        // 设置路由
        app.use(settings.httpAdminRoot, RED.default.httpAdmin);
        app.use(settings.httpNodeRoot, RED.default.httpNode);
        
        // 启动服务器
        server.listen(settings.uiPort, () => {
            console.log(`🚀 Node-RED已启动`);
            console.log(`📡 Node-RED服务器运行在端口 ${settings.uiPort}`);
            console.log(`📊 管理界面: http://localhost:${settings.uiPort}${settings.httpAdminRoot}`);
            console.log(`🔌 API端点: http://localhost:${settings.uiPort}${settings.httpNodeRoot}`);
            
            // 启动Node-RED运行时
            RED.default.start().then(() => {
                console.log('✅ Node-RED运行时已启动');
            }).catch(err => {
                console.error('❌ Node-RED运行时启动失败:', err);
            });
        });
        
        // 优雅关闭
        process.on('SIGINT', () => {
            RED.default.stop().then(() => {
                server.close(() => {
                    process.exit(0);
                });
            });
        });
        
    } catch (err) {
        console.error('❌ Node-RED启动失败:', err);
        process.exit(1);
    }
}

// 启动服务
startNodeRed();